package com.example.demo.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapListMerger {

    public static List<Map<String, String>> mergeMaps(List<Map<String, String>> inputList) {
        Map<String, String> mergedMap = new HashMap<>();
        for (Map<String, String> map : inputList) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();

                if (mergedMap.containsKey(key)) {
                    // 如果已存在该key，将值进行拼接（这里以逗号分隔为例，可按需修改）
                    // mergedMap.put(key, mergedMap.get(key) + "," + value);
                    mergedMap.computeIfPresent(key,(k,v)-> v + "," + value);
                } else {
                    mergedMap.put(key, value);
                }
            }
        }

        List<Map<String, String>> resultList = new ArrayList<>();
        resultList.add(mergedMap);
        return resultList;
    }

    public static void main(String[] args) {
        List<Map<String, String>> inputList = new ArrayList<>();
        Map<String, String> map1 = new HashMap<>();
        map1.put("key1", "value1");
        map1.put("key2", "value2");
        inputList.add(map1);

        Map<String, String> map2 = new HashMap<>();
        map2.put("key1", "value3");
        map2.put("key2", "value4");
        inputList.add(map2);

        List<Map<String, String>> mergedList = mergeMaps(inputList);
        for (Map<String, String> map : mergedList) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                System.out.println(entry.getKey() + ": " + entry.getValue());
            }
        }
    }
}